const userModel = require("../model/user")
const bcrypt = require('bcryptjs');
const {saltStep,jwtStep,port,host} = require("../config")
const salt = bcrypt.genSaltSync(saltStep);
const jwt = require('jsonwebtoken');
module.exports = {
    //前端拥有对应功能的
    //登出
    async logout(ctx){
        //后台应该将当前登录的token拉入黑名单!!
        ctx.body =  {
            code: 20000,
            data: 'success'
        }
    },
    //获取用户信息
    async info(ctx){
        let id = ctx.loginUser.id;
        //{username,roles}
        const user = await userModel.findById(id);
        ctx.body = {
            code: 20000,
            data: user
        }
    },
    //登录
    async login(ctx){
        const {name,pwd} = ctx.request.body;
        //1. 判断是否有这个用户
        const users = await userModel.find({username:name}).select("+pwd")
        if(users.length === 0) {
            ctx.body = {
                code: 60204,
                message: 'Account and password are incorrect.'
            }
            return;
        }
        //2. 如果有这个用户 判断密码是否正确(pwd是明文的,currentPwd是密文的)
        let {username,pwd:currentPwd,_id,roles} = users[0];
        let checkResult = bcrypt.compareSync(pwd, currentPwd);
        if(!checkResult){
            ctx.body = {
                code: 60204,
                message: 'Account and password are incorrect.'
            }
            return;
        }
        //3. 如果密码正确 返回登录令牌
        const token = jwt.sign({id:_id,name:username,roles}, jwtStep, { expiresIn: "7d" });
        // ctx.cookies.set("token", token)
        ctx.body = {
            code:20000,
            data:{
                token
            }
        }
    },


    //前端没有对应功能的
    //上传头像
    async avatar(ctx){
        //1.拿到图片 2.将图片上传到静态资源服务器 koaBody配置中实现

        //3.返回头像的地址
        if(!ctx.request.files.avatar){
            ctx.status = 422;
            ctx.body = "没有图片资源";
            ctx.throw(422,"没有图片资源")
        }
        let paths = ctx.request.files.avatar.path.split("\\");
        let path = paths.pop();
        let avatarUrl = `http://127.0.0.1:8089/img/${path}`;

        //4.将头像地址入数据库
        let id = ctx.loginUser.id;
        await userModel.findByIdAndUpdate(id,{ $set: { avatar: avatarUrl }})
        ctx.status = 200
        ctx.body = avatarUrl
    },
    //注册(员工新增)
    async register(ctx){
        const {name,pwd,roles} = ctx.request.body;
        //1. 判断用户名是否重复
        const users = await userModel.find({username:name})
        if(users.length > 0) ctx.throw(409,"该用户已注册");
        //2. 没有该用户 可注册 为密码加盐加密(密码在数据库中要密文存储)
        const pwd_hash = bcrypt.hashSync(pwd, salt);
        //3. 注册
        let newUser = await userModel.create({
            username:name,
            pwd:pwd_hash,
            roles
        });
        newUser = await userModel.findById(newUser._id)
        ctx.status = 200;
        ctx.body={code:200,data:newUser}
    }
}